package net.cyl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class NetcatSimulator {
    public static void main(String[] args) {
        int port = 8888;

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务器已启动，监听端口 " + port);

            while (true) {
                // 等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接：" + clientSocket.getInetAddress());

                // 为每个客户端创建一个新线程处理
                new ClientHandler(clientSocket).start();
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败，端口可能被占用：" + e.getMessage());
        }
    }

    private static class ClientHandler extends Thread {
        private final Socket clientSocket;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }

        @Override
        public void run() {
            try (
                    // 获取客户端输入流
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(clientSocket.getInputStream()));

                    // 获取客户端输出流
                    PrintWriter out = new PrintWriter(
                            clientSocket.getOutputStream(), true)
            ) {
                String inputLine;
                // 读取客户端发送的数据并回显
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("客户端消息：" + inputLine);
                    out.println("服务器已收到：" + inputLine);
                }
            } catch (IOException e) {
                System.err.println("处理客户端连接时出错：" + e.getMessage());
            } finally {
                try {
                    clientSocket.close();
                    System.out.println("客户端连接已关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}